<template>
  <div class="message-detail-container">
    <div class="header">
      <h1>消息详情</h1>
      <div class="breadcrumb">我的消息 > 消息详情</div>
    </div>

    <div class="message-detail" v-if="message">
      <p class="message-content">{{ message.content }}</p>
      <span class="timestamp">{{ message.timestamp }}</span>
      <p class="read-status" :class="{ 'unread': !message.read }">
        {{ message.read ? '已读' : '未读' }}
      </p>
      <!-- 根据订单状态判断是否显示发货按钮 -->
      <el-button v-if="message.orderStatus === '待接单'" type="primary" @click="shipOrder">发货</el-button>
      <!-- 根据订单状态判断是否显示收货按钮 -->
      <el-button v-if="message.orderStatus === '已发货'" type="primary" @click="receiveOrder">收货</el-button>
    </div>

    <div class="notice-box" v-else>
      <p>消息不存在或已删除。</p>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from 'element-plus';

const route = useRoute();
const router = useRouter();
const message = ref(null);
const loading = ref(false);
const error = ref(null);

// 获取消息详情
const fetchMessageDetail = async () => {
  const id = route.params.id;
  loading.value = true;
  
  try {
    // 先尝试从卖家消息获取
    let response = await axios.get(`http://localhost:3000/sellermessages/${id}`);
    message.value = response.data;
    
    // 如果没找到，尝试从买家消息获取
    if (!message.value) {
      response = await axios.get(`http://localhost:3000/buyermessages/${id}`);
      message.value = response.data;
    }
    
    // 获取订单状态
    if (message.value && message.value.orderId) {
      const orderResponse = await axios.get(`http://localhost:3000/orders/${message.value.orderId}`);
      message.value.orderStatus = orderResponse.data.status;
    }
  } catch (err) {
    error.value = err.message;
  } finally {
    loading.value = false;
  }
};

// 发货操作
const shipOrder = async () => {
  if (!message.value || !message.value.orderId) return;
  
  try {
    // 更新订单状态为已发货
    await updateOrderStatus(message.value.orderId, '已发货');
    
    // 更新卖家消息为已读
    await axios.patch(`http://localhost:3000/sellermessages/${message.value.id}`, { read: true });
    
    // 发送通知给买家（存储到buyermessages）
    const buyerId = message.value.userId;
    const buyerNotification = {
      sellerId: message.value.sellerId,
      userId: buyerId,
      orderId: message.value.orderId,
      content: "您的订单已发货，请注意收货",
      timestamp: new Date().toISOString(),
      read: false
    };
    await axios.post('http://localhost:3000/buyermessages', buyerNotification);
    
    ElMessage.success('订单已发货');
    router.push('/main/profile/message-center');
  } catch (error) {
    console.error('发货失败:', error);
    ElMessage.error('发货失败，请重试');
  }
};

// 收货操作
const receiveOrder = async () => {
  if (!message.value || !message.value.orderId) return;
  
  try {
    // 更新订单状态为已完成
    await updateOrderStatus(message.value.orderId, '已完成');
    
    // 更新买家消息为已读
    await axios.patch(`http://localhost:3000/buyermessages/${message.value.id}`, { read: true });
    
    ElMessage.success('订单已收货');
    router.push('/main/profile/message-center');
  } catch (error) {
    console.error('收货失败:', error);
    ElMessage.error('收货失败，请重试');
  }
};

// 定义 updateOrderStatus 方法
const updateOrderStatus = async (orderId, newStatus) => {
  try {
    await axios.patch(`http://localhost:3000/orders/${orderId}`, { status: newStatus });
  } catch (error) {
    throw error;
  }
};

onMounted(() => {
  fetchMessageDetail();
});
</script>

<style scoped>
.message-detail-container {
  padding: 20px;
}

.header {
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
  margin-bottom: 20px;
}

.header h1 {
  margin: 0;
  font-size: 24px;
}

.breadcrumb {
  color: #999;
  font-size: 14px;
}

.message-detail {
  background: #ffffff;
  border-radius: 10px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.message-content {
  margin: 0;
  margin-bottom: 10px;
}

.timestamp {
  color: #999;
  font-size: 12px;
}

.read-status {
  margin-top: 10px;
  color: #999;
}

.unread {
  color: #e05649;
}

.notice-box {
  margin-top: 20px;
  padding: 10px;
  background: #f8f8f8;
  border: 1px solid #eee;
  border-radius: 4px;
  color: #999;
  font-size: 14px;
  text-align: center;
}
</style>